package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.GetSessionId;
import com.itheima.common.Result;
import com.itheima.pojo.Employee;
import com.itheima.service.ServiceDemo;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private ServiceDemo serviceDemo;


    /**
     * 验证登录
     *
     * @param employee
     * @param req
     * @return
     */
    @PostMapping("/login")
    public Result<Employee> login(@RequestBody Employee employee, HttpServletRequest req) {
        String username = employee.getUsername();

        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, username);
        Employee emp = serviceDemo.getOne(lqw);

        if (emp == null) {
            return Result.error("用户不存在");
        }

        String password = employee.getPassword();
        String s = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!emp.getPassword().equals(s)) {
            return Result.error("密码错误");
        }


        if (emp.getStatus() == 0) {
            return Result.error("该账户已停用");
        }

        HttpSession session = req.getSession();
        session.setAttribute("Employee", emp.getId());

        return Result.success(emp);
    }


    //退出系统
    //    http://localhost:8080/employee/logout
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest req) {

        //1.注销session
        HttpSession session = req.getSession();
        session.invalidate();

        return Result.success("退出成功");
    }


    //分页
    //http://localhost:8080/employee/page?page=1&pageSize=10
    //http://localhost:8080/employee/page?page=1&pageSize=10&name=???
    @GetMapping("/page")
    public Result page(int page, int pageSize, String name) {

//        //当前页
//        page
//        //每页显示的条目数
//        pageSize

        IPage pages = new Page<>(page, pageSize);

        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Employee::getName, name).orderByDesc(Employee::getCreateTime);
        IPage result = serviceDemo.page(pages, lqw);

        List<Employee> records = result.getRecords();

        long total = result.getTotal();

        Map<String, Object> map = new HashMap<>();
        map.put("records", records);
        map.put("total", total);

        return Result.success(map);
    }


    //修改数据回显
    //请求 URL: http://localhost:8080/employee/1
    @GetMapping("/{id}")
    public Result<Employee> goBack(@PathVariable Long id) {

        Employee one = serviceDemo.getById(id);
        return Result.success(one);
    }


    /**
     * 修改员工信息
     *
     * @param employee
     * @param req
     * @return
     */
    //请求 URL: http://localhost:8080/employee
    @PutMapping
    public Result UpdateSingle(@RequestBody Employee employee, HttpServletRequest req) {

//        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String format = LocalDateTime.now().format(dtf);
//        LocalDateTime localDateTime = LocalDateTime.parse(format, dtf);
//        employee.setUpdateTime(localDateTime);
//
//        HttpSession session = req.getSession();
//        Long id = (Long) session.getAttribute("Employee");
//        employee.setUpdateUser(id);
        if (employee.getId() == 1 && employee.getStatus() == 0) {
            return Result.error("该账户为管理员,不能被禁用");
        }

        boolean result = serviceDemo.updateById(employee);
        if (!result) {
            return Result.error("修改失败");
        }

        return Result.success("修改成功");
    }


    /**
     * 添加员工信息
     *
     * @param employee
     * @return
     */
    //请求 URL: http://localhost:8080/employee
    @PostMapping
    public Result save(@RequestBody Employee employee) {
        //判断用户名是否存在
//        String name = employee.getName();
//        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Employee::getName, name);
//        Employee one = serviceDemo.getOne(lqw);
//        if (one != null) {
//            return Result.error("用户名已存在");
//        }


        //设置参数
//        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

//        String format = LocalDateTime.now().format(dtf);
//
//        LocalDateTime localDateTime = LocalDateTime.parse(format, dtf);
//        employee.setCreateTime(localDateTime);
//        employee.setUpdateTime(localDateTime);
//
//        HttpSession session = req.getSession();
//        Long id = (Long) session.getAttribute("Employee");
//        employee.setCreateUser(id);
//        employee.setUpdateUser(id);
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        boolean save = serviceDemo.save(employee);
        if (!save) {
            return Result.error("添加成功");
        }
        return Result.success(save);
    }


    //     Request URL: http://localhost:8080/employee/check
//        Request Method: POST
    @PostMapping("/check")
    public Result checkPwd(@RequestBody Map<String, Integer> map) {
        Integer initPass = map.get("initPass");
        if (initPass == null) {
            return Result.error("请输入原密码");
        }
        Integer pass = map.get("pass");
        Integer checkPass = map.get("checkPass");

        if (pass == null || checkPass == null) {
            return null;
        }

        Long employeeId = GetSessionId.GetId();
        Employee one = serviceDemo.getById(employeeId);
        String password = one.getPassword();

        String initPassword = DigestUtils.md5DigestAsHex(initPass.toString().getBytes());

        if (!initPassword.equals(password)) {
            return Result.error("原密码输入有误");
        }

        if (pass != checkPass) {
            return null;
        }


        String pwd = DigestUtils.md5DigestAsHex(pass.toString().getBytes());
        one.setPassword(pwd);
        serviceDemo.updateById(one);

        return Result.success("修改成功");
    }
}
